
// 视频播放页面上需要的一个混入。
import request from '@/utils/nvue-request' 
const activeVideoRuleStatus = {
	start: 1,
	end: 2,
	random: 3
}
const cDurationField = 'duration'
export default {
	data() {
		return {
			current: 0,
			durationField: 'duration',
			// 视频 时长 ，秒级单位
			videoDownTime: 0,
			lotteryVisible: false,
			lotteryDrawingVisible: false,
			videoList: [],
			videoContext: null,
			activeRedEnvelopeInfo: {},
			redEnvelopeList: [],
			videoIsEnd: false,
			videoIsPause: false,
			videoIsPlay: false,
			
			
		}
	},
	computed: {
		// 当前正在播放的视频数据
		activeVideo() {
			if (this.current >=0 && this.videoList.length && this.current < this.videoList.length) {
				const active = this.videoList[this.current]
				if (active) {
					return active;
				}
				return {}
			}
			return {}
		},
		// 是否是领过了红包 0 表示可以领 true, 1表示已经领过了 false，所以不能领.
		isPopUp(){
			if (!Object.keys(this.activeVideo).length) {
				return false
			}
			// 等于0可以领,。
			return this.activeVideo.pop_up === 0
		},
		activeVideoRule() {
			if( this.activeVideo.rule && typeof this.activeVideo.rule === 'object') {
				return this.activeVideo.rule 
			}
			return {}
		},
		/**
		 * 红包领取规则。1 表示视频开始 时播放，2表示结束时领取，3表示随机
		 */
		activeVideoRuleValue() {
			return this.activeVideoRule.rule || activeVideoRuleStatus.end
		},
		// 根据红包领取规则 判断是否需要倒计时
		isNeedDownTime() {
			return this.isPopUp && this.activeVideoRuleValue !== activeVideoRuleStatus.start
		},
		videoDuration() {
			
			if (this.activeVideoRuleValue === activeVideoRuleStatus.start) {
				return 0
			}
			if (!Object.keys(this.activeVideo).length) {
				console.log('activeVideo 不存在，或者是个空对象', 0)
				return 0
			}
			
			let time = this.activeVideo[cDurationField]
			time = time ? Number(time) : 0
			if (this.activeVideoRuleValue === activeVideoRuleStatus.end) {
				console.log('视频长度', time)
				return time
			}
			
			const maxTime = time
			const minTime = time / 5
			const retTime = Math.floor( Math.random() * (time - minTime) + minTime )
			console.log('videoDuration4 activeVideoRuleStatus.rondom', retTime)
			return retTime

			
		}
		
	},
	
	mounted(){
		this.$nextTick(() => {
			if (this.$refs.lotteryPopup) {
				this.$refs.lotteryPopup.open('right')
			}
		})
		
	},
	methods: {
		startPlay() {
			
		},
		/**
		 * 视频开始播放时的动作。要做两个判断，
		 * 一个是该视频是否已经领过了红包， pop_up
		 *  还有就是 是否是结束时 领红包。
		 */
		videoStartLotteryHandler() {
			this.videoIsEnd = false
			this.videoIsPause = false
			this.videoIsPlay = true
			if (!this.isPopUp) {
				return
			}
			if (this.activeVideoRuleValue === activeVideoRuleStatus.start) {
				this.lotteryOpenHandler()
			}
			
		},
		pauseHandler(e) {
			this.videoIsPause = true
		},
		/**
		 * 视频结束时的动作。要做两个判断，
		 * 一个是该视频是否已经领过了红包，
		 * 还有就是 是否是结束时 领红包。
		 */
		videoEndLotteryHandler(){
			this.videoIsEnd = true
			this.videoIsPause = true
			this.videoIsPlay = false
			let current = this.current + 1
			if (current >= this.videoList.length) {
				current = 0
			}
			if (!this.isPopUp) {
				this.change({
					detail: {
						current:current
					}
				})
				return
			}
			if (this.activeVideoRuleValue === activeVideoRuleStatus.end) {
				this.lotteryOpenHandler()
			}
			
		},
		videoThreeLotteryHandler(){
			
			if (!this.isPopUp) {
				return
			}
			if (this.activeVideoRuleValue === activeVideoRuleStatus.random && this.videoDownTime <= 1) {
				this.lotteryOpenHandler()
			}
		},
		/**
		 * 在打开弹窗之前，应该先获取中奖金额。
		 * 然后暂停视频。再根据 activeVideoRuleValue 状态，是继续播放，还是播放下一个视频
		 */
		lotteryOpenHandler() {
			
			if (this.videoContext && this.videoContext.pause) {
				console.log("视频暂停了没有")
				this.videoContext.pause()
			}
			uni.showLoading({
				title: '加载中……'
			})
			
			request.post('supply_video.videoRed/grantRedEnvelope', {
				video_id: this.activeVideo.id
			}).then((res) => {
				// 等于1 的时候，才可以弹出红包抽奖.
				//@todo 后台接口,暂时还没做好。先模似下数据。
				this.activeRedEnvelopeInfo = res
				this.redEnvelopeList = this.redEnvelopeListCreate(res)
				this.lotteryVisible = true
				// console.log("lotteryOpenHandler", res)
				
			}).catch((err) => {
				console.log(err)
				this.closeAfter()
			}).finally(() => {
				uni.hideLoading()
			});
		},
		/**
		 * @param {Object} params 红包列表生成，最大值，最小值，当前红包
		 */
		redEnvelopeListCreate(params) {
			const list = []
			const start_money = Number(params.start_money)
			const end_money = Number(params.end_money)
			list.push({
				id: params.red_id,
				min: start_money,
				max: end_money,
				content: params.money,
				selectId: params.red_id,
			})
			for (let i = 0; i< 5; i++) {
				const activeMoney = Number((Math.random() * (end_money - start_money) + start_money).toFixed(2))
				list.push({
					id: i === params.red_id ? Math.floor(Math.random() * 100 + 100) : i,
					min: start_money,
					max: end_money,
					content: activeMoney,
					selectId: params.red_id,
				})
			}
			return list.sort(() => Math.random() - 0.5);
		},
		
		// 抽奖页面关闭时的动作
		closeLottery() {
			
			this.lotteryVisible = false
			this.closeAfter()
		},
		openLotteryDrawing() {
			// 这个红包id,不知道是后台的哪个字段。
			uni.showLoading({
				title: '正在领取红包……'
			})
			this.videoList[this.current].pop_up = 1
			request.post('supply_video.videoRed/receiveRedEnvelope', {
				red_id: this.activeRedEnvelopeInfo.red_id
			}).then((res) => {
				this.lotteryVisible = false
				this.lotteryDrawingVisible = true
			}).catch((err) => {
				this.lotteryVisible = false
				this.lotteryDrawingVisible = true
			}).finally(() => {
				uni.hideLoading()
			});
			
		},
		closeAfter() {
			this.videoList[this.current].pop_up = 1
			console.log("this.videoList[this.current]", this.videoList[this.current], this.isNeedDownTime)
			if (this.activeVideoRuleValue === 2) {
				if (this.current < this.videoList.length - 1) {
					// 有则自动翻到下一个视频, 切换到下一个视频前，要把倒计时归零
					let current = this.current + 1
					if (current >= this.videoList.length) {
						current = 0
					}
					this.change({
						detail: {
							current: current
						}
					})
				}
				return
			}
			if (this.videoContext && this.videoContext.play) {
				this.videoContext.play()
			}
			
		},
		closeLotteryDrawing() {
			this.lotteryVisible = false
			this.lotteryDrawingVisible = false
			
			this.closeAfter()
		},
		
		/**
		 * 进度条发生变化时做的一个事。理论上来说，只需要这一个事件就行，其内部甚至都不需要倒计时。
		 * @param {Object} item
		 * @param {Object} $event
		 */
		timeupdateHandler(item, $event) {
			this.videoIsEnd = false
			this.videoIsPause = false
			this.videoIsPlay = false
			const eventDetails = $event?.detail || {}
			const duration = eventDetails.duration
			const currentTime = eventDetails.currentTime
			// console.log("进度条更新了1", duration)
			if (!duration) {
				return
			}
			if (this.activeVideoRuleValue === 1) {
				return
			}
			
			
			// console.log("进度条更新了2", duration)
			if (this.activeVideoRuleValue === 2) {
				if (!this.videoList[this.current][cDurationField]) {
					this.videoList[this.current][cDurationField] = duration
					// this.videoDuration = duration
				}
				this.videoThreeLotteryHandler()
				// console.log("进度条更新了2", this.videoDownTime)
				return
			}
			
			const maxTime = duration
			const minTime = duration / 5
			const time = Math.floor( Math.random() * (duration - minTime) + minTime )
			
			// if (!this.videoDuration) {
			// 	this.videoDuration = time
			// }
			
			this.videoThreeLotteryHandler()
		}
	}
}